﻿using HslCommunication.Profinet.Siemens;
using Sunny.UI;
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LaserMark
{
    public partial class MainForm : UIForm
    {
        private SiemensS7Net siemensS7;

        /// <summary>
        /// 上次请求
        /// </summary>
        private short LastRequest { get; set; }

        /// <summary>
        /// 上次回复
        /// </summary>
        private int LastResponse { get; set; }

        /// <summary>
        /// 产品编码
        /// </summary>
        private string RecipeName { get; set; }

        /// <summary>
        /// 产品型号
        /// </summary>
        private int RecipeNumber { get; set; }

        private int LeftOrRight { get; set; }
        private Configuration config;
        private string totalWidth = ConfigurationManager.AppSettings["TotalWidth"];
        private string subLength = ConfigurationManager.AppSettings["SubLength"];
        private string filePath = ConfigurationManager.AppSettings["FilePath"];
        private string ip = ConfigurationManager.AppSettings["IP"];
        private string dbRecipeName = ConfigurationManager.AppSettings["RecipeName"];
        private string dbRecipeNumber = ConfigurationManager.AppSettings["RecipeNumber"];
        private string dbLeftOrRight = ConfigurationManager.AppSettings["LeftOrRight"];
        private string dbRequest = ConfigurationManager.AppSettings["Request"];
        private string dbResponse = ConfigurationManager.AppSettings["Response"];
        private string dbHeartResponse = ConfigurationManager.AppSettings["HeartResponse"];

        private string DBStr = ConfigurationManager.AppSettings["DataBase"];

        public MainForm()
        {
            InitializeComponent();
            this.Load += MainForm_Load;
            this.FormClosing += MainForm_FormClosing;
            this.btn_total.Click += Btn_total_Click;
            this.btn_file.Click += Btn_file_Click;
            this.btn_sub.Click += Btn_sub_Click;
        }

        private void Btn_sub_Click(object sender, EventArgs e)
        {
            config.AppSettings.Settings["SubLength"].Value = txt_sub.Text;
            subLength = txt_sub.Text;
            config.Save();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show("您确定要退出当前程序吗？", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result != DialogResult.OK)
            {
                e.Cancel = true;
            }
        }

        private void Btn_file_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "选择一个文件";
            openFileDialog.Filter = "文本文件 (*.txt)|*.txt";
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                txt_filePath.Text = filePath;
                config.AppSettings.Settings["FilePath"].Value = txt_filePath.Text;
                config.Save();
            }
        }

        private void Btn_total_Click(object sender, EventArgs e)
        {
            config.AppSettings.Settings["TotalWidth"].Value = txt_totalWidth.Text;
            config.Save();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //string beforeDate = ConfigurationManager.AppSettings["CurrentDate"];

            //string CurrentDate = DateTime.Now.ToString("yyMMdd");
            ////新的一天重新赋值
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //if (CurrentDate != beforeDate)
            //{
            //    config.AppSettings.Settings["CurrentSerialNumber"].Value = "0";
            //    config.AppSettings.Settings["CurrentDate"].Value = CurrentDate;
            //    config.Save();
            //}

            txt_totalWidth.Text = totalWidth;
            txt_filePath.Text = filePath;
            txt_sub.Text = subLength;
            Start();
        }

        /// <summary>
        /// 信号读取
        /// </summary>
        private void Start()
        {
            Task.Run(() =>
            {
                Thread.Sleep(100);
                while (true)
                {
                    if (siemensS7 == null)
                    {
                        siemensS7 = new SiemensS7Net(SiemensPLCS.S1200);
                        siemensS7.IpAddress = ip;
                        siemensS7.Port = 102;
                        siemensS7.ConnectTimeOut = 2000;
                        siemensS7.SetPersistentConnection();
                    }
                    try
                    {
                        //心跳信号
                        siemensS7.WriteAsync(dbHeartResponse, (short)(DateTime.Now.Second % 2));

                        RecipeName = siemensS7.ReadString(dbRecipeName).Content;
                        RecipeNumber = siemensS7.ReadInt16(dbRecipeNumber).Content;
                        LeftOrRight = siemensS7.ReadInt16(dbLeftOrRight).Content;
                        var request = siemensS7.ReadInt16(dbRequest).Content;
                        var response = siemensS7.ReadInt16(dbResponse).Content;
                        if (request != LastRequest && request == (short)1)
                        {
                            LastRequest = request;
                            this.BeginInvoke(new Action(() =>
                            {
                                lbl_status.Text = "收到工作信号......";
                            }));
                            AssembleBarcode();
                        }
                        if (request == (short)0)
                        {
                            LastRequest = 0;
                            this.BeginInvoke(new Action(() =>
                            {
                                txt_barCode.Text = "";
                                lbl_status.Text = "等待工作信号中......";
                            }));
                        }
                    }
                    catch
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            lbl_status.Text = "数据读取失败......";
                        }));
                    }
                    Thread.Sleep(200);
                }
            });
        }

        /// <summary>
        /// 条码组合
        /// </summary>
        /// <exception cref="Exception"></exception>
        private async void AssembleBarcode()
        {
            try
            {
                string CurrentDate = DateTime.Now.ToString("yyMMdd");
                //DateTime now = DateTime.Now;
                //string CurrentDate2 = now.ToString("yyMMddHH") + ":" + now.ToString("mm"); ;
                if (CurrentDate != config.AppSettings.Settings["CurrentDate"].Value)
                {
                    config.AppSettings.Settings["CurrentSerialNumber"].Value = "0";
                    config.AppSettings.Settings["CurrentDate"].Value = CurrentDate;
                    config.Save();
                }
                string CurrenttotalWidth = config.AppSettings.Settings["TotalWidth"].Value;
                string CurrentFilePath = config.AppSettings.Settings["FilePath"].Value;
                string beforeNumber = config.AppSettings.Settings["CurrentSerialNumber"].Value;
                string CurrentProductCode = "";
                if (RecipeName != null)
                {
                    CurrentProductCode = RecipeName.Substring(0, Convert.ToInt32(subLength));
                }
                string CurrentProductBA = RecipeNumber % 2 == 0 ? "R3" : "F3";
                string CurrentProductLR = LeftOrRight == 2 ? "R" : "L";
                int CurrentSerialNmber = Convert.ToInt32(beforeNumber) + 1;
                string FinalBarcode;

                MarkCode(CurrentDate, CurrentProductCode, CurrentProductBA, CurrentProductLR, CurrentSerialNmber, CurrenttotalWidth, out FinalBarcode);
                //MarkCode2(CurrentDate2, CurrentSerialNmber, CurrenttotalWidth, out FinalBarcode);
                File.WriteAllText(CurrentFilePath, FinalBarcode);
                siemensS7.Write(dbResponse, (short)1);
                this.BeginInvoke(new Action(() =>
                {
                    txt_barCode.Text = FinalBarcode;
                    lbl_productCode.Text = CurrentProductCode;
                    lbl_ba.Text = RecipeNumber % 2 == 0 ? "后" : "前";
                    lbl_lr.Text = LeftOrRight == 2 ? "右" : "左";
                    lbl_num.Text = CurrentSerialNmber.ToString();
                    lbl_status.Text = "信息发送完成......";
                }));
                config.AppSettings.Settings["CurrentSerialNumber"].Value = CurrentSerialNmber.ToString();
                config.Save();
            }
            catch (Exception ex)
            {
                this.BeginInvoke(new Action(() =>
                {
                    lbl_status.Text = ex.Message;
                }));
            }
        }

        public void MarkCode2(string CurrentDate, int CurrentSerialNmber, string CurrenttotalWidth, out string FinalBarcode)
        {
            FinalBarcode = CurrentDate + "\n" + CurrentSerialNmber.ToString().PadLeft(Convert.ToInt32(CurrenttotalWidth), '0');
            FinalBarcode = FinalBarcode + "\n" + CurrentDate + CurrentSerialNmber.ToString().PadLeft(Convert.ToInt32(CurrenttotalWidth), '0');
        }

        /// <summary>
        /// 条码判断递归
        /// </summary>
        /// <param name="CurrentDate"></param>
        /// <param name="CurrentProductCode"></param>
        /// <param name="CurrentProductBA"></param>
        /// <param name="CurrentProductLR"></param>
        /// <param name="CurrentSerialNmber"></param>
        /// <param name="CurrenttotalWidth"></param>
        /// <returns></returns>
        private void MarkCode(string CurrentDate, string CurrentProductCode, string CurrentProductBA, string CurrentProductLR, int CurrentSerialNmber, string CurrenttotalWidth, out string FinalBarcode)
        {
            try
            {
                FinalBarcode = CurrentDate + CurrentProductCode + CurrentProductBA + CurrentProductLR + CurrentSerialNmber.ToString().PadLeft(Convert.ToInt32(CurrenttotalWidth), '0');
                //using (SqlConnection db = new SqlConnection(DBStr))
                //{
                //    db.Open();
                //    string str = $"Select * from station_work_info Where station_code='OP40_50_60' and product_id='{FinalBarcode}'";
                //    using (SqlCommand command = new SqlCommand(str, db))
                //    {
                //        var readCount = command.ExecuteScalar();
                //        if (readCount != null && (int)readCount > 0)
                //        {
                //            MarkCode(CurrentDate, CurrentProductCode, CurrentProductBA, CurrentProductLR, CurrentSerialNmber + 1, CurrenttotalWidth, out FinalBarcode);
                //        }
                //        else
                //        {
                //        }
                //    }
                //}
            }
            catch (Exception)
            {
                FinalBarcode = null;
            }
        }
    }
}